<!-- 团队邀请模态框组件 -->
<template>
  <view v-if="show" class="modal-overlay" @click="closeModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">邀请好友加入团队</text>
        <button class="close-btn" @click="closeModal">×</button>
      </view>
      
      <view class="modal-body">
        <!-- 团队名称输入 -->
        <view class="input-group">
          <text class="input-label">团队名称</text>
          <input 
            v-model="teamName" 
            placeholder="请输入团队名称" 
            class="team-name-input"
          />
        </view>
        
        <!-- 搜索好友 -->
        <view class="input-group">
          <text class="input-label">搜索好友</text>
          <view class="search-container">
            <input 
              v-model="searchKeyword" 
              placeholder="输入好友昵称或ID" 
              class="search-input"
              @input="onSearchInput"
            />
            <button class="search-btn" @click="searchFriends">
              <text>搜索</text>
            </button>
          </view>
        </view>
        
        <!-- 搜索结果 -->
        <view v-if="searchResults.length > 0" class="search-results">
          <text class="results-title">搜索结果</text>
          <view 
            v-for="friend in searchResults" 
            :key="friend.uid" 
            class="friend-item"
          >
            <image 
              :src="getAvatarUrl(friend.avatarUrl)" 
              class="friend-avatar"
              @error="handleAvatarError"
            />
            <view class="friend-info">
              <text class="friend-name">{{ friend.nickname }}</text>
              <text class="friend-id">ID: {{ friend.uid }}</text>
            </view>
            <button 
              v-if="!isUserInvited(friend.uid)"
              class="invite-btn"
              @click="inviteSingleUser(friend.uid)"
              :disabled="inviting"
            >
              <text>邀请</text>
            </button>
            <button 
              v-else
              class="invited-btn"
              disabled
            >
              <text>已邀请</text>
            </button>
          </view>
        </view>
        
        <!-- 好友列表 -->
        <view v-if="friends.length > 0" class="friends-list">
          <text class="list-title">我的好友</text>
          <view 
            v-for="friend in friends" 
            :key="friend.uid" 
            class="friend-item"
          >
            <image 
              :src="getAvatarUrl(friend.avatarUrl)" 
              class="friend-avatar"
              @error="handleAvatarError"
            />
            <view class="friend-info">
              <text class="friend-name">{{ friend.nickname }}</text>
              <text class="friend-id">ID: {{ friend.uid }}</text>
            </view>
            <button 
              v-if="!isUserInvited(friend.uid)"
              class="invite-btn"
              @click="inviteSingleUser(friend.uid)"
              :disabled="inviting"
            >
              <text>邀请</text>
            </button>
            <button 
              v-else
              class="invited-btn"
              disabled
            >
              <text>已邀请</text>
            </button>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="friends.length === 0 && searchResults.length === 0" class="empty-state">
          <text class="empty-text">暂无好友</text>
        </view>
      </view>
      
      <view class="modal-footer">
        <button class="cancel-btn" @click="closeModal">
          <text>取消</text>
        </button>
        <button class="confirm-btn" @click="confirmInvitation" :disabled="inviting">
          <text>确定邀请</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { NETWORK_CONFIG } from '@/config/network.js'

// Props
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  taskId: {
    type: [Number, String],
    required: true
  },
  teamInfo: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['close', 'invite-success'])

// 响应式数据
const teamName = ref('临时团队')
const searchKeyword = ref('')
const searchResults = ref([])
const friends = ref([])
const invitedUsers = ref(new Set())
const inviting = ref(false)
const loading = ref(false)

// 计算属性
const show = computed(() => props.show)

// 方法
const getAvatarUrl = (avatarUrl) => {
  if (!avatarUrl) return '/static/images/default-avatar.png'
  if (avatarUrl.startsWith('http')) return avatarUrl
  return `${NETWORK_CONFIG.API_BASE_URL}${avatarUrl}`
}

const handleAvatarError = () => {
  console.log('头像加载失败')
}

const onSearchInput = () => {
  if (searchKeyword.value.trim()) {
    searchFriends()
  } else {
    searchResults.value = []
  }
}

const searchFriends = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }
  
  loading.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends/search`,
      method: 'POST',
      data: {
        keyword: searchKeyword.value.trim()
      },
      header: {
        'Access-Token': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data && response.data.success) {
      searchResults.value = response.data.data || []
    } else {
      searchResults.value = []
    }
  } catch (error) {
    console.error('搜索好友失败:', error)
    searchResults.value = []
  } finally {
    loading.value = false
  }
}

const loadFriends = async () => {
  loading.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends/list`,
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.success) {
      friends.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载好友列表失败:', error)
  } finally {
    loading.value = false
  }
}

const inviteSingleUser = async (friendId) => {
  if (inviting.value) return
  
  inviting.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    const currentUser = uni.getStorageSync('userInfo')
    
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }
    
    let leaderId = null
    if (currentUser && currentUser.uid) {
      leaderId = currentUser.uid
    } else {
      try {
        const tokenPayload = JSON.parse(atob(token.split('.')[1]))
        leaderId = tokenPayload.uid || tokenPayload.sub
      } catch (tokenError) {
        console.error('解析token失败:', tokenError)
        return
      }
    }
    
    if (!leaderId) return
    
    // 检查是否尝试邀请自己
    if (String(leaderId) === String(friendId)) {
      uni.showToast({ title: '不能邀请自己加入团队', icon: 'none' })
      return
    }
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/team/send-invitation`,
      method: 'POST',
      data: {
        taskId: Number(props.taskId),
        leaderId: Number(leaderId),
        teamName: teamName.value.trim() || '临时团队',
        inviteeIds: [Number(friendId)]
      },
      header: {
        'Access-Token': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data && response.data.success) {
      uni.showToast({
        title: '邀请发送成功',
        icon: 'success'
      })
      markUserAsInvited(friendId)
    } else {
      uni.showToast({
        title: response.data?.message || '发送邀请失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发送邀请失败:', error)
    uni.showToast({
      title: '发送邀请失败',
      icon: 'none'
    })
  } finally {
    inviting.value = false
  }
}

const markUserAsInvited = (friendId) => {
  invitedUsers.value.add(friendId)
}

const isUserInvited = (friendId) => {
  return invitedUsers.value.has(friendId)
}

const confirmInvitation = () => {
  emit('invite-success')
  closeModal()
}

const closeModal = () => {
  emit('close')
}

// 监听显示状态
watch(show, (newShow) => {
  if (newShow) {
    loadFriends()
  } else {
    // 重置状态
    searchKeyword.value = ''
    searchResults.value = []
    invitedUsers.value.clear()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 16rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  font-size: 32rpx;
  border: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  flex: 1;
  padding: 30rpx;
  overflow-y: auto;
}

.input-group {
  margin-bottom: 30rpx;
}

.input-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 15rpx;
  display: block;
}

.team-name-input,
.search-input {
  width: 100%;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  background: #fff;
}

.search-container {
  display: flex;
  gap: 20rpx;
}

.search-input {
  flex: 1;
}

.search-btn {
  padding: 20rpx 30rpx;
  background: #2196F3;
  color: white;
  border-radius: 12rpx;
  font-size: 26rpx;
  border: none;
}

.search-results,
.friends-list {
  margin-top: 30rpx;
}

.results-title,
.list-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 15rpx;
}

.friend-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.friend-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.friend-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 5rpx;
}

.friend-id {
  font-size: 24rpx;
  color: #666;
}

.invite-btn,
.invited-btn {
  padding: 16rpx 32rpx;
  border-radius: 12rpx;
  font-size: 26rpx;
  font-weight: 500;
  border: none;
  min-width: 120rpx;
}

.invite-btn {
  background: #4CAF50;
  color: white;
}

.invite-btn:disabled {
  background: #ccc;
  color: #999;
}

.invited-btn {
  background: #e0e0e0;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60rpx;
  color: #999;
  font-size: 28rpx;
}

.modal-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #4CAF50;
  color: white;
}

.confirm-btn:disabled {
  background: #ccc;
  color: #999;
}
</style>
